<div class="row">
    <div class="colxl-12 col-lg-12 col-md-12 col-sm-12 col-12">
        <div class="page-title-wrapper">
            <div class="page-title-box">
                <h4 class="page-title bold">导航网址</h4>
            </div>
            <div class="breadcrumb-list">
                <ul>
                    <li class="breadcrumb-link"><a th:href="@{admin}"><i class="fas fa-home mr-2"></i>首页</a></li>
                    <li class="breadcrumb-link active">网站管理</li>
                    <li class="breadcrumb-link active">导航网址</li>
                </ul>
            </div>
        </div>
    </div>
</div>
<!-- Main content -->
<div class="row">
    <div class="col-lg-2 col-md-3">
        <div class="card card-body">
            <div class="compose-btn"><h3>导航分类</h3></div>
            <ul id="categoryTree" class="ztree"></ul>
        </div>
    </div>
    <div class="col-lg-10 col-md-9">
    <div class="card card-info card-header">
        <form id="searchForm" class="needs-validation form-inline" novalidate="">
            <div class="form-group">
                <label for="name">站点名称:</label>
                <input type="text" class="form-control m-2" id="name" required="">
            </div>
            <div class="form-group">
                <label for="url">站点链接:</label>
                <input type="text" class="form-control m-2" id="url" required="">
            </div>
            <div class="form-group">
                <button class="btn btn-primary ml-3" type="submit">查询</button>
                <button class="btn btn-light ml-2" type="reset">重置</button>
            </div>
        </form>
    </div>
    <div class="card table-card card-body">
        <div id="toolbar" class="btn-group">
                <button id="btn_add" type="button" class="btn btn-primary">
                    <span class="fa fa-plus" aria-hidden="true"></span>新增网站
                </button>
                <button id="btn_edit_category" type="button" class="btn btn-warning">
                    <span class="fa fa-bahai" aria-hidden="true"></span>修改分类
                </button>
                <button id="btn_batch_delete" type="button" class="btn btn-danger">
                    <span class="fa fa-trash" aria-hidden="true"></span>批量删除
                </button>
        </div>
        <table class="table-sm" id="table"></table>
    </div>
    </div>
</div>

<!-- 表单模态框 -->
<div class="modal fade" id="formModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="formTitle"></h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div id="formContent"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveOrUpdateBtn">保存
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 权限分配模态框 -->
    <div class="modal fade" id="categoryModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="assignPermissionTitle">修改分类</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <ul id="modalTree" class="ztree"></ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" id="websiteCopyBtn" >复制</button>
                    <button type="button" class="btn btn-primary" id="websiteMoveBtn">移动
                    </button>
                </div>
            </div>
        </div>
    </div>
<script>
    $(function () {
        let categoryId = [[${categoryId}]];
        //树-初始化设置
        var treeSetting = {
            view: {
              //  showIcon: false,
                selectedMulti: false        //禁止多点选中
            },
            //增删改，移动复制
            edit: {
              //  enable: true, //如果enable为flase，那么树就不能移动了
              //  showRemoveBtn: true, //是否显示树的删除按钮
             //   showRenameBtn: true, //是否显示数的重命名按钮
              //  isSimpleData: true, //数据是否采用简单 Array 格式，默认false
                // treeNodeKey: "id",  //在isSimpleData格式下，当前节点id属性,根据需要自己更改
                //  treeNodeParentKey: "pid",//在isSimpleData格式下，当前节点的父节点id属性，根据需要自己更改
                //showLine: true, //是否显示节点间的连线
           //     removeTitle: "删除节点",//删除Logo的提示
            //    renameTitle: "编辑节点",//修改Logo的提示
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pid"
                }
            },
            callback: {
                onClick: onClick,//左点击触发的函数
                onRightClick: onRightClick //右击触发的函数
            }
        };
        Core.postAjax("/category/list", {}, function (data) {
            const zTree = $.fn.zTree.init($("#categoryTree"), treeSetting, data);
            const node = zTree.getNodeByParam("id", categoryId);
            zTree.selectNode(node);
        });
        //鼠标点击节点的函数
        function onClick(event, treeId, treeNode) {
            //当node里具有url的时候，阻止跳转
            event.preventDefault();//阻止页面跳转
            categoryId=treeNode.id;
            refreshTable();
        }
        //鼠标点击节点的函数
        function onRightClick(event, treeId, treeNode) {

        }
        window.operateEvents = {
            // 点击编辑
            'click .btn_edit': function (e, value, row, index) {
                editRow(row.id)
            },
            // 点击删除
            'click .btn_del': function (e, value, row, index) {
                deleteRow(row.id)
            },
            // 点击预览
            'click .btn_view': function (e, value, row, index) {
                previewImg(row.img.base64)
            }
        }
        const columns = [
            {checkbox: true},
            {
                field: 'name',
                title: '站点名称',
                align: "center"
            }, {
                field: 'url',
                title: '站点链接',
                align: "center",
                formatter: function (value, row, index) {
                    return '<a href="' + value + '" target="_blank">' + value.replace('//', '') + '</a>'
                }
            }, {
                field: 'description',
                title: '站点描述',
                align: "center",
            }, {
                field: 'img.base64',
                title: '站长图片',
                align: "center",
                class: "link-pre",
                events: operateEvents,
                formatter: function (value, row, index) {
                    return '<img src="' + value + '" style="height: 40px;" class="btn_view" referrerPolicy="no-referrer" />'
                }
            },
            /*      {
                     field: 'email',
                     title: '站长邮箱',
                     align : "center",
                 },{
                     field: 'qq',
                     title: '站长QQ',
                     align : "center",
                 },
              {
                     field: 'status',
                     title: '状态',
                     align : "center",
                     formatter: typeSwitch
                 }, */
            {
                field: 'operation',
                title: '操作',
                align: "center",
                width: 200,
                events: operateEvents,
                formatter: operationFormatter
            }];
        const onLoadSuccess = function () {	//在成功加载远程数据时触发
            $("[name='switch']").bootstrapSwitch({
                onText: "启用",      // 设置ON文本
                offText: "禁用",    // 设置OFF文本
                onColor: "success",// 设置ON文本颜色(info/success/warning/danger/primary)
                offColor: "warning",  // 设置OFF文本颜色 (info/success/warning/danger/primary)
                size: "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
                // 当开关状态改变时触发
                onSwitchChange: function (event, state) {
                    var status = state ? 1 : 0;
                    var params = {id: this.value, status: status};
                    var str = jQuery.param(params);
                    Core.postAjax('/website/edit', str, function (data) {
                        if (data.status === 200) {
                            refreshTable();
                        }
                        layer.msg(data.msg);
                    })
                }
            });
        };
        function operationFormatter(value, row, index) {
            const edit = '<button class="effect-btn btn btn-info mt-2 mr-2 icon-lg btn_edit"><i class="fas fa-edit"></i></button>';
            const del = '<button class="effect-btn btn btn-danger mt-2 mr-2 icon-lg btn_del"><i class="fas fa-trash-alt"></i></button>';
            return edit + del;
        }

        const options = {
            id: "#table",
            url: '/website/list',
            columns: columns,
            toolbar: '#toolbar',
            showRefresh: true,
            onLoadSuccess: onLoadSuccess,
            queryParams: queryParams
        };
        Core.initTable(options);

        function refreshTable() {
            Core.refreshTable("#table")
        }

        // 查询参数
        function queryParams(params) {
            console.log(params)
            return {
                pageNumber: params.pageNumber,
                pageSize: params.pageSize,
                name: $("#name").val(),
                url: $("#url").val(),
                categoryId:categoryId,
                status: $("#status").val(),
            };
        }

        // 查询
        $('#searchForm').submit(function (event) {
            event.preventDefault();
            event.stopPropagation();
            refreshTable();
        })

        // 新增
        $('#btn_add').on('click', function () {
            Core.load("#formContent", "/website/add", function () {
                $('#formTitle').text('新增')
                $("#formModal").modal('show');
            });
        })
        //只是在点击后初始化的时候生成
        $("#formModal").on("shown.bs.modal", function () {
            // 初始化Web Uploader
            const uploader = WebUploader.create({
                // 选完文件后，是否自动上传。
                auto: true,
                // swf文件路径
                swf: '/admin/img/Uploader.swf',
                // 文件接收服务端。
                server: '[[@{/image/upload}]]',
                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: '#filePicker',
                // 只允许选择图片文件。
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png,ico',
                    mimeTypes: 'image/*'
                }
            });
            // 文件上传成功，给item添加成功class, 用样式标记上传成功。
            uploader.on( 'uploadSuccess', function( file,data ) {
                $("#imageId").val(data.imageId);
                $("#img").attr("src",data.base64);
            });
            // 文件上传失败，显示上传出错。
            uploader.on( 'uploadError', function( file ) {
                console.log('上传失败');
            });
        })

        // 编辑
        function editRow(id) {
            Core.load("#formContent", "/website/edit?id=" + id, function () {
                $('#formTitle').text('编辑')
                $("#formModal").modal('show');
            });
            Core.initTable(options);
        }

        // 删除
        function deleteRow(id) {
            Core.confirm("确定删除？", function () {
                Core.postAjax("/website/delete", {"id": id}, function (data) {
                    if (data.status === 200) {
                        Core.initTable(options);
                    }
                    layer.msg(data.msg);
                })
            })
        }
        //树-初始化设置
        const setting = {
            view: {
                showIcon: false,
                selectedMulti: false //禁止多点选中
            },
            check: {
                enable: true,
                chkStyle: "radio",
                checkStrictly: true,// 禁止部分选中，设为 true
                radioType: "all",
                chkboxType: {"Y": "ps", "N": "s"}
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pid"
                }
            },
            callback: {
                onClick: onClickNode//左点击触发的函数
            }
        };
        let zzTree;
        //修改分类
        $("#btn_edit_category").on('click', function () {
            const checkedRows = Core.selectMutiData("#table");
            if (checkedRows) {
                Core.postAjax("/category/list", {}, function (data) {
                     zzTree=$.fn.zTree.init($("#modalTree"), setting, data);
                     const node = zzTree.getNodeByParam("id", categoryId);
                     zzTree.checkNode(node);
                    $("#categoryModal").modal("show");
                })
            }else {
                layer.msg("请选中需要修改的网址！");
            }
        });

        //鼠标点击节点的函数
        function onClickNode(event, treeId, treeNode) {
            //当node里具有url的时候，阻止跳转
            event.preventDefault();//阻止页面跳转
            zzTree.checkNode(treeNode);
        }

        $('#websiteMoveBtn').on('click', function () {
            Core.mask("#websiteMoveBtn");
            const checkedRows = Core.selectMutiData("#table");
            if (checkedRows) {
                const treeObj = $.fn.zTree.getZTreeObj("modalTree");
                const nodes = treeObj.getCheckedNodes(true);
                if(nodes.length>0){
                    const ids = [];
                    $.each(checkedRows, function (i, item) {
                        ids.push(item.id);
                    })
                    const jsonStr = JSON.stringify(ids);
                    Core.postAjax("/website/move/"+nodes[0].id, jsonStr, function (data) {
                        if (data.status === 200) {
                            refreshTable();
                            Core.unmask("#websiteMoveBtn");
                            $("#categoryModal").modal("hide");
                        }
                        layer.msg(data.msg);
                    },function (err) {
                        layer.msg(err)
                    }, "application/json; charset=UTF-8")
                }
            }
        })

        $('#websiteCopyBtn').on('click', function () {
            Core.mask("#websiteCopyBtn");
            const checkedRows = Core.selectMutiData("#table");
            if (checkedRows) {
                const treeObj = $.fn.zTree.getZTreeObj("modalTree");
                const nodes = treeObj.getCheckedNodes(true);
                console.log(nodes)
                if(nodes.length>0){
                    const ids = [];
                    $.each(checkedRows, function (i, item) {
                        ids.push(item.id);
                    })
                    const jsonStr = JSON.stringify(ids);
                    Core.postAjax("/website/copy/"+nodes[0].id, jsonStr, function (data) {
                        if (data.status === 200) {
                            refreshTable();
                            Core.unmask("#websiteCopyBtn");
                            $("#categoryModal").modal("hide");
                        }
                        layer.msg(data.msg);
                    },function (err) {
                        layer.msg(err)
                    },"application/json; charset=UTF-8")
                }
            }
        })


        // 批量删除
        $("#btn_batch_delete").on('click', function () {
            var checkedRows = Core.selectMutiData("#table");
            if (checkedRows) {
                Core.confirm("确定删除选中的" + checkedRows.length + "条记录？", function () {
                    var ids = [];
                    $.each(checkedRows, function (i, item) {
                        ids.push(item.id);
                    })
                    var jsonStr = JSON.stringify(ids);
                    Core.postAjax("/website/batch/delete", jsonStr, function (data) {
                        if (data.status === 200) {
                            refreshTable();
                        }
                        layer.msg(data.msg);
                    },function (err) {
                        layer.msg(err)
                    }, "application/json; charset=UTF-8")
                })
            }
        })

        // 保存或更新
        $('#saveOrUpdateBtn').on('click', function () {
            var $f = $('#websiteForm');
            let dataParam=$f.serialize();
            dataParam =dataParam +"&"+"categoryId="+categoryId;
            var valid = $f[0].checkValidity();
            var url = $f.find("input[name='id']").val() ? "/website/edit" : "/website/add"
            if (valid) {
                Core.mask("#saveOrUpdateBtn");
                Core.postAjax(url, dataParam, function (data) {
                    Core.unmask("#saveOrUpdateBtn");
                    if (data.status === 200) {
                        $("#formModal").modal("hide");
                        refreshTable();
                    }
                    layer.msg(data.msg);
                }, function () {
                    Core.unmask("#saveOrUpdateBtn");
                })
            }
            $f.addClass("was-validated")
        })

    });
    function previewImg(src) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            area: '45%',
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            content: '<img style="width: 100%" alt="link" src="' + src + '">'
        });
    }

</script>